﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
#if NET40
using System.Runtime.InteropServices;
#endif
using SAM.Framework.Machine;

namespace SAM.Framework.Machine
{
    public class DefaultMachineProvider : IMachineProvider
    {

        public DefaultMachineProvider()
        {

        }

        public MachineInfo GetMachineInfo()
        {
            MachineInfo machineInfo = new MachineInfo();

            machineInfo.CpuNum = this.GetProperty("Win32_Processor", (moc) =>
            {
                string val = string.Empty;
                foreach(var m in moc)
                {
                    val = m.Properties["ProcessorId"].Value.ToString();
                }
                return val;
            });

            machineInfo.Mac = this.GetProperty("Win32_NetworkAdapterConfiguration", (moc) =>
            {
                string val = string.Empty;
                foreach (var m in moc)
                {
                    if ((bool)m["IPEnabled"] == true)
                    {
                        val = m["MacAddress"].ToString();
                    }
                }
                return val;
            });

            machineInfo.DiskNum = this.GetProperty("Win32_DiskDrive", (moc) =>
            {
                string val = string.Empty;
                foreach (var m in moc)
                {
                    val = (string)m.Properties["Model"].Value;
                }
                return val;
            });

            return machineInfo;
        }

        private string GetProperty(string key, Func<ManagementObjectCollection, string> func)
        {
            try
            {
#if NET40
                ManagementClass mc = new ManagementClass(key);
#else 
                ManagementClass mc = new ManagementClass(key);  //根据issue#26137 会在.net core2.1.0中加入支持
#endif
                ManagementObjectCollection moc = mc.GetInstances();
                string value = func(moc);
                moc = null;
                mc = null;
                return value;
            }catch(Exception ex)
            {
                return "unknow";
            }

        }
    }
}
